package com.windea.study.kotlin.jvm.crypt.sections

import com.windea.study.kotlin.jvm.crypt.extensions.*
import javax.crypto.*
import javax.crypto.spec.*

/**
 * AES加密算法。
 * 对原始二进制数据进行操作。
 * 密钥长度为16字节.
 */
object AesCrypt {
	fun encrypt(input: ByteArray, key: ByteArray): ByteArray {
		val keySpec = SecretKeySpec(key, "AES")
		val cipher = Cipher.getInstance("AES")
		cipher.init(Cipher.ENCRYPT_MODE, keySpec)
		return cipher.doFinal(input)
	}
	
	fun encrypt(input: String, key: String): String {
		//需要对结果进行base64编码
		return encrypt(input.encodeToByteArray(), key.encodeToByteArray()).encodeBase64().decodeToString()
	}
	
	fun decrypt(input: ByteArray, key: ByteArray): ByteArray {
		val keySpec = SecretKeySpec(key, "AES")
		val cipher = Cipher.getInstance("AES")
		cipher.init(Cipher.DECRYPT_MODE, keySpec)
		return cipher.doFinal(input)
	}
	
	fun decrypt(input: String, key: String): String {
		//需要对输入进行base64解码
		return decrypt(input.encodeToByteArray().decodeBase64(), key.encodeToByteArray()).decodeToString()
	}
}
